import {
  Divider,
  Table,
  Switch,
  Button,
  Space,
  Pagination,
  Modal,
  Form,
  Input,
  Select,
  message
} from "antd";
import { useState, useEffect, useRef } from "react";
import { getRoleInfo } from "../../../utils/gethttp";
import { AddRoleInfo } from "../../../utils/Addhttp";
import { delRoleInfo } from "../../../utils/delhttp";
import { upDateRoleInfo } from "../../../utils/updatehttp";
import { getMemberInfo } from "../../../utils/getMemberInfo";
import "./index.scss";

const Student = () => {
  const [selectionType, setSelectionType] = useState("checkbox");
  const columns = [
    {
      title: "序号",
      dataIndex: "roleId",
    },
    {
      title: "角色名称",
      dataIndex: "roleName",
    },
    {
      title: "职能描述",
      dataIndex: "roleDetail",
    },
    {
      title: "成员",
      dataIndex: "roleMember",
    },
    {
      title: "创建时间",
      dataIndex: "roleCreateTime",
      render: (text, record) => {
        console.log(text, record);
        const dateStr = record.rolecCreateTime;
        const date = new Date(dateStr);
        date.setDate(date.getDate() + 1);
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, "0");
        const day = String(date.getDate() - 1).padStart(2, "0");
        const formattedDate = `${year}-${month}-${day}`; // "2023-04-10"

        return <span>{formattedDate}</span>;
      },
    },
    {
      title: "是否启用",
      dataIndex: "roleEnable",
      align: "center",
      render: (text, record, index) => {
        return (
          <Switch
            defaultChecked={record.roleEnable}
            disabled
            checked={record.roleEnable}
          

          />
        );
      },
    },
    {
      title: "操作",
      align: "center",
      render: (text, record, index) => {
        return (
          <Space>
            <a onClick={()=>{
              upDate(record)
            }}>编辑</a>
            <a onClick={()=>{
               delRole(record,index)
            }}>删除</a>
          </Space>
        );
      },
    },
  ];
  const [dataList, setDataList] = useState([]);
  const [delData,setDelData]=useState([])
  const [canData,setCanData]=useState([])
  const data = [...dataList];


 

  // const ChangeSwitch = (checked) => {
  //   console.log(checked);
  // };
  // rowSelection object indicates the need for row selection
  const rowSelection = {
    onChange: (selectedRowKeys, selectedRows) => {
      console.log(
        `selectedRowKeys: ${selectedRowKeys}`,
        "selectedRows: ",
        selectedRows
      );
    },
    getCheckboxProps: (record) => ({
      name: record.name,
    }),
  };
 const getRole = () => {
  let admin=0
  let member=0
  let user=0
  getMemberInfo()
  .then((res) => {
    console.log(res.data, "res");
   for(let i=0;i<res.data.length;i++){
      if(res.data[i].user_type=='管理员'){
         admin++
      }
      else if(res.data[i].user_type=='成员'){
        member++
      }
      else if(res.data[i].user_type=='用户'){
        user++
      }
   }
  //  console.log(admin,'admin');
  //  console.log(member,'member');
  //  console.log(user,'user');

  })
  .catch((err) => {
    console.log(err, "err");
  });
    getRoleInfo()
      .then((res) => {
        console.log(res.data, "res");
        const list = res.data.map((item) => ({ ...item, key: item.roleId }));
        console.log(list, "list");
        for(let i=0;i<list.length;i++){
        if(list[i].roleName=='管理员'){
            list[i].roleMember=admin
         }
         else if(res.data[i].roleName=='成员'){
              list[i].roleMember=member

         }
         else if(res.data[i].roleName=='用户'){
            list[i].roleMember=user
         }
        }
        setDataList(list);
        console.log(admin,'admin');
        console.log(member,'member');
        console.log(user,'user');
      })
      .catch((err) => {
        console.log(err, "err");
      });


  };

  const AddRole = (data) => {
    AddRoleInfo(data)
      .then((res) => {

        console.log(res.data, "res");
        getRole()


      })
      .catch((err) => {
        console.log(err, "err");
      });
  };
  const upDateRole=(data)=>{
    upDateRoleInfo(data)
      .then((res) => {
        console.log(res.data, "res");
          getRole() 

      })
      .catch((err) => {
        console.log(err, "err");
      });
  }
  const delInfo=(data)=>{
    delRoleInfo(data)
      .then((res) => {
        console.log(res.data, "res");
      getRole()

      })
      .catch((err) => {
        console.log(err, "err");
      });(data)
  }
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [isOpen,setIsopen]=useState(false)
  const [old,setOld]=useState([])
  const ok = (values) => {
    if (values.roleEnable == undefined) {
      values.roleEnable = true;
    }
    console.log("onFinishok", values);
    console.log(addForm, "addform");
    if (values) {
      const now = new Date();
      const year = now.getFullYear();
      const month = String(now.getMonth() + 1).padStart(2, "0");
      const day = String(now.getDate()).padStart(2, "0");
      const hours = String(now.getHours()).padStart(2, "0");
      const minutes = String(now.getMinutes()).padStart(2, "0");
      const seconds = String(now.getSeconds()).padStart(2, "0");

      const datetime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
      console.log(datetime,'datetime');
      let list=[]
      list.push(values)
      let listData=list.map((item) => ({ ...item, rolecCreateTime: datetime }))
      console.log(listData,'66');
      AddRole(listData)
      addForm.current.resetFields();
      setIsModalOpen(false)
      message.success({
        type: 'success',
        content: '添加成功!'
      });
    }
  };
  const FailedOk = (values) => {
    console.log("onFinishFailed:", values);

  };
  const upOk = (values) => {
    console.log(values,'是大苏打');
    if (values.roleEnable == undefined) {
      values.roleEnable = true;
    }
    console.log("onFinishok", values);
    console.log(addForm, "addform");
    if (values) {
      const now = new Date();
      const year = now.getFullYear();
      const month = String(now.getMonth() + 1).padStart(2, "0");
      const day = String(now.getDate()).padStart(2, "0");
      const hours = String(now.getHours()).padStart(2, "0");
      const minutes = String(now.getMinutes()).padStart(2, "0");
      const seconds = String(now.getSeconds()).padStart(2, "0");

      const datetime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
      console.log(datetime,'datetime');
      let list=[]
      list.push(values)
      console.log(old.roleId,'old');
      let listData=list.map((item) => ({ ...item, roleId: old.roleId }))
      console.log(listData,'6666');
      upDateRole(listData)
      addForm.current.resetFields();
      setIsopen(false)
      message.success({
        type: 'success',
        content: '修改成功!'
      });
    }
  };
  const cancel = (values) => {
    console.log("onFinishFailed:", values);

  };
  const addBtn = () => {
    console.log(111);

    setIsModalOpen(true);
  };
  const { TextArea } = Input;
  const onChange = (e) => {
    console.log("Change:", e.target.value);
  };
  const onChange2 = (e) => {
    console.log("Change:", e.target.value);
  };
  const onSwitch = (checked) => {
    console.log(`switch to ${checked}`);
  };
  const onSwitch2 = (checked) => {
    console.log(`switch to ${checked}`);
  };
  const [value, setValue] = useState(null);
  const [value2,setValue2]=useState(null)
  const handleFocus = () => {
    setValue("");
  };
  const handleFocus2 = () => {
    setValue2("");
  };
  const addForm = useRef();
  const delRole=(data)=>{
    console.log('赖总');
    console.log(data,'delRole');
    delInfo(data)
    message.success({
      type: 'success',
      content: '删除成功!'
    });
  }
  let list=[]
  const upDate=(data,index)=>{
    console.log('路总');
    console.log(data,'编辑');
    setOld(data)
    list=data
    setCanData(data)
    console.log(canData,'编辑表格');
    setIsopen(true);


  }
  useEffect(() => {
    getRole();
    
   }, []);
  useEffect(() => {
    console.log(old, '编辑');
    console.log(canData, '编辑表格');
  
  }, [old, canData]);
  return (
    <div>
      <h1>角色管理</h1>
      <Divider />
      <Button
        className={"addBtn"}
        onClick={() => {
          addBtn();
        }}
      >
        添加
      </Button>
      <Table
        rowSelection={{
          type: selectionType,
          ...rowSelection,
        }}
        columns={columns}
        dataSource={data}
      />
      <Pagination
        className={"Pagination"}
        total={1}
        showSizeChanger
        showQuickJumper
        showTotal={(total) => `共 ${total} 页`}
      />
      <>
        <Modal title="添加角色" open={isModalOpen} footer={null}>
          <Form
            className={"form1"}
            name="basic"
            labelCol={{ span: 8 }}
            wrapperCol={{ span: 16 }}
            style={{ maxWidth: 600 }}
            onFinish={ok}
            onFinishFailed={FailedOk}
            autoComplete="off"
            ref={addForm}
            initialValues={delData}
          >
            <Form.Item
              label="角色名称"
              name="roleName"
              rules={[{ required: true, message: "角色名称不能为空" }]}
            >

              <Input />
            </Form.Item>
            <Form.Item
              label="职能描述"
              name="roleDetail"
              rules={[{ required: true, message: "职能描述不能为空" }]}
            >
              <TextArea
                showCount
                maxLength={50}
                onChange={onChange}
                style={{ height: "120px" }}
                placeholder="职能描述不超过50个字"
                value={value}
                onFocus={handleFocus}
              />
            </Form.Item>
            <Form.Item
              label="是否启用"
              name="roleEnable"
              valuePropName="checked"
            >
              <Switch defaultChecked onChange={onSwitch} value={value} />
            </Form.Item>
            <Form.Item className="btn">
              <Button type="primary" htmlType="submit" 
              >
                保存
              </Button>
              <Button
                htmlType="button"
                style={{ marginLeft: "20px" }}
                onClick={() => {
                   setIsModalOpen(false);
                   
                }}
              >
                取消
              </Button>
            </Form.Item>
          </Form>
        </Modal>
      </>
      <>
        <Modal title="编辑角色" open={isOpen} footer={null} destroyOnClose={true}>
          <Form
            className={"form2"}
            name="basic"
            labelCol={{ span: 8 }}
            wrapperCol={{ span: 16 }}
            style={{ maxWidth: 600 }}
            onFinish={upOk}
            onFinishFailed={cancel}
            autoComplete="off"
            ref={addForm}
            initialValues={canData}
          >
            <Form.Item
              label="角色名称"
              name="roleName"
              rules={[{ required: true, message: "角色名称不能为空" }]}
            >
              
              <Input />
            </Form.Item>
            <Form.Item
              label="职能描述"
              name="roleDetail"
              rules={[{ required: true, message: "职能描述不能为空" }]}
            >
              <TextArea
                showCount
                maxLength={50}
                onChange={onChange2}
                style={{ height: "120px" }}
                placeholder="职能描述不超过50个字"
                value={value2}
                onFocus={handleFocus2}
              />
            </Form.Item>
            <Form.Item
              label="是否启用"
              name="roleEnable"
              valuePropName="checked"
            >
              <Switch defaultChecked onChange={onSwitch2} value={value} checked={canData.roleEnable} />
            </Form.Item>
            <Form.Item className="btn">
              <Button type="primary" htmlType="submit" 
              >
                保存
              </Button>
              <Button
                htmlType="button"
                style={{ marginLeft: "20px" }}
                onClick={() => {
                  setIsopen(false);
                   
                }}
              >
                取消
              </Button>
            </Form.Item>
          </Form>
        </Modal>
      </>
    </div>
  );
};

export default Student;
